Skip to content

Latest commit

 

History

History
84 lines (68 loc) · 1.8 KB

File metadata and controls

84 lines (68 loc) · 1.8 KB

1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal tok. The same Fibonacci number can be used multiple times.

The Fibonacci numbers are defined as:

  • F1 = 1
  • F2 = 1
  • Fn = Fn-1 + Fn-2 for n > 2.

It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.

Example 1:

Input: k = 7 Output: 2 Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ... For k = 7 we can use 2 + 5 = 7. 

Example 2:

Input: k = 10 Output: 2 Explanation: For k = 10 we can use 2 + 8 = 10. 

Example 3:

Input: k = 19 Output: 3 Explanation: For k = 19 we can use 1 + 5 + 13 = 19. 

Constraints:

  • 1 <= k <= 10^9

Solutions (Ruby)

1. Greedy

# @param {Integer} k# @return {Integer}deffind_min_fibonacci_numbers(k)nums=[1,1]ret=0nums.push(nums[-2] + nums[-1])whilenums[-1] < kwhilek > 0nums.popwhilenums[-1] > kk -= nums[-1]ret += 1endretend

Solutions (Rust)

1. Greedy

implSolution{pubfnfind_min_fibonacci_numbers(mutk:i32) -> i32{letmut nums = vec![1,1];letmut i = 1;letmut ret = 0;while nums[i] < k { nums.push(nums[i - 1] + nums[i]); i += 1;}while k > 0{while nums[i] > k { i -= 1;} k -= nums[i]; ret += 1;} ret }}
close